//
//  CollectViewController.m
//  STL_ Animation
//
//  Created by 孙健 on 16/3/30.
//  Copyright © 2016年 STL. All rights reserved.
//

#import "CollectViewController.h"
#import "AppDelegate.h"
#import "STL.h"
#import "CoreDataManager.h"
#import "MusicYue_V_TableViewCell.h"
#import "MVCollection.h"
#import "YSingleCollection.h"
#import "MusicYue_V_Model.h"
#import "YSingleCollectTableViewCell.h"
#import "YSingleCollectModel.h"
#import "ChannelPageMV_ViewController.h"
#import "YMVViewController.h"
#import "HomePageBaseModel.h"
#import "STLAvPlayer.h"
#import "STLPopup_window.h"
#import "MvLoad.h"
#import "STLLoadMv.h"

@interface CollectViewController ()<UITableViewDelegate, UITableViewDataSource, STLPopup_windowDelegate>

@property (nonatomic, strong) CoreDataManager *coreDataManager;
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
@property (nonatomic, strong) STLTableView * tableView;
@property (nonatomic, strong) STLView *segBackgroundView;
@property (nonatomic, strong) STLImageView *backImageView;

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *mvCollectArr;
@property (nonatomic, strong) NSMutableArray *ySingleCollectArr;

@property (nonatomic, strong) STLAvPlayer *avPlayer;

@property (nonatomic, assign) NSInteger count;
@end

@implementation CollectViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"收藏列表";
    
    self.dataSource = [NSMutableArray arrayWithCapacity:0];
        self.mvCollectArr = [NSMutableArray arrayWithCapacity:0];
        self.ySingleCollectArr = [NSMutableArray arrayWithCapacity:0];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(YSingleCollectReloadAction:) name:@"CollectReload" object:nil];
    
    self.avPlayer = [STLAvPlayer shareAVPlayer];
    
    [self creatSegemented];
    [self creatTableView];
    [self creatBackImageView];
    self.coreDataManager = [CoreDataManager shareCoreDataManager];
    NSLog(@"%@", [self.coreDataManager applicationDocumentsDirectory]);
    
    [self loadMVDate];
    
}

#pragma mark - YSingleCollectReload通知
- (void)YSingleCollectReloadAction:(NSNotification *)message {
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        [self loadMVDate];
    } else {
        [self loadYSingleDate];
    }
}

#pragma mark - 读取MV表给数组赋值
- (void)loadMVDate {
    self.backImageView.hidden = YES;
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MVCollection" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%@", error);
    } else {
        
        [self.dataSource removeAllObjects];
        [self.mvCollectArr removeAllObjects];
        
        for (MVCollection *mvCollect in fetchedObjects) {
            
            [self.mvCollectArr addObject:mvCollect];
            
            MusicYue_V_Model *model = [[MusicYue_V_Model alloc] init];
            
            model.idName = [NSNumber numberWithInteger:mvCollect.idName.integerValue];
            model.title = mvCollect.title;
            model.artistName = mvCollect.artistName;
            model.posterPic = mvCollect.posterPic;
            model.uhdUrl = mvCollect.hdUrl;
            model.totalViews = mvCollect.totalViews;
            model.albumImg = mvCollect.albumImage;
            [self.dataSource addObject:model];
        }
        
        // 使数组倒序 最近的播放历史在最上方
        self.dataSource = [NSMutableArray arrayWithArray:[[self.dataSource reverseObjectEnumerator] allObjects]];
        self.mvCollectArr = [NSMutableArray arrayWithArray:[[self.mvCollectArr reverseObjectEnumerator] allObjects]];
        
        if (self.dataSource.count == 0) {
            NSLog(@"没有MV");
            self.backImageView.hidden = NO;
        }
        [self.tableView reloadData];
    }
}

#pragma mark - 读取悦单表给数组赋值
- (void)loadYSingleDate {
    self.backImageView.hidden = YES;
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"YSingleCollection" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%@", error);
    } else {
        
        [self.dataSource removeAllObjects];
        [self.ySingleCollectArr removeAllObjects];
        
        for (YSingleCollection *ySingleCollect in fetchedObjects) {
            
            [self.ySingleCollectArr addObject:ySingleCollect];
            
            YSingleCollectModel *model = [[YSingleCollectModel alloc] init];
            model.Id = [NSNumber numberWithInteger:ySingleCollect.detailId.integerValue];
            model.title = ySingleCollect.title;
            model.listPic = ySingleCollect.listImage;
            model.videoCount = ySingleCollect.videoCount;
            model.nickName = ySingleCollect.nickName;
            model.creatorImage = ySingleCollect.creatImage;
            model.totalViews = ySingleCollect.totalViews;
            model.integral = ySingleCollect.intergral;
            model.artistName = ySingleCollect.artistName;
            [self.dataSource addObject:model];
        }
        if (self.dataSource.count == 0) {
            NSLog(@"没有悦单");
            self.backImageView.hidden = NO;
        }
        [self.tableView reloadData];
    }
}
#pragma mark - creatSegmented
- (void)creatSegemented {
    self.segBackgroundView = [[STLView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight * 0.045 + 5)];
    self.segBackgroundView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.segBackgroundView];
    
    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"MV收藏", @"悦单的收藏"]];
    self.segmentedControl.frame = CGRectMake(5, 0, ScreenWidth - 10, ScreenHeight * 0.045);
    self.segmentedControl.selectedSegmentIndex = 0;
    self.segmentedControl.tintColor = [UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:1];
    [self.segmentedControl setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected];
    [self.segmentedControl addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segmentedControl];
}
#pragma mark - segementedAction
- (void)segmentedAction:(UISegmentedControl *)sender {
    if (sender.selectedSegmentIndex == 0) {
        [self loadMVDate];
    } else {
        [self loadYSingleDate];
    }
}

- (void)creatBackImageView {
    self.backImageView = [[STLImageView alloc] initWithFrame:CGRectMake(0, self.segBackgroundView.bounds.size.height, ScreenWidth, 400)];
    self.backImageView.image = [UIImage imageNamed:@"collectBack"];
    self.backImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.backImageView.hidden = YES;
    [self.view addSubview:self.backImageView];
}

#pragma mark - creatTableView
- (void)creatTableView {
    self.tableView = [[STLTableView alloc] initWithFrame:CGRectMake(0, self.segBackgroundView.bounds.size.height, ScreenWidth, ScreenHeight - self.segBackgroundView.bounds.size.height - 60) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[MusicYue_V_TableViewCell class] forCellReuseIdentifier:@"MusicYue_V_TableViewCellIdentifier"];
    [self.tableView registerClass:[YSingleCollectTableViewCell class] forCellReuseIdentifier:@"YSingleCollectTableViewCellIdentifier"];
    
    [self.view addSubview:self.tableView];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        return ScreenWidth / 4;
    }
    return ScreenHeight / 4;
}

#pragma mark - editingTableView
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"😄");
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        [self.dataSource removeObjectAtIndex:indexPath.row];
        
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
        
        if (self.segmentedControl.selectedSegmentIndex == 0) {
            
            [self.coreDataManager.managedObjectContext deleteObject:self.mvCollectArr[indexPath.row]];
            [self.mvCollectArr removeObjectAtIndex:indexPath.row];
            
        } else {
            
            [self.coreDataManager.managedObjectContext deleteObject:self.ySingleCollectArr[indexPath.row]];
            [self.ySingleCollectArr removeObjectAtIndex:indexPath.row];
        }
        [self.coreDataManager saveContext];
    }
    if (self.dataSource.count == 0) {
        self.backImageView.hidden = NO;
    }
    
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        MusicYue_V_TableViewCell *mvCell = [tableView dequeueReusableCellWithIdentifier:@"MusicYue_V_TableViewCellIdentifier"];
        mvCell.selectionStyle = UITableViewCellSelectionStyleNone;
        mvCell.musicModel = self.dataSource[indexPath.row];
        
        mvCell.count = indexPath.row;
        __weak CollectViewController *collectVC = self;
        mvCell.block = ^(NSInteger count) {
            
            STLPopup_window *popUpWindow = [[STLPopup_window alloc] initWithFrame:collectVC.view.bounds with:@[@"下载", @"分享"]];
            popUpWindow.delegate = self;
            [collectVC.view addSubview:popUpWindow];
            collectVC.count = count;
            NSLog(@"%ld", count);
        };
        return mvCell;
    } else {
        YSingleCollectTableViewCell *ySingleCell = [tableView dequeueReusableCellWithIdentifier:@"YSingleCollectTableViewCellIdentifier"];
        ySingleCell.selectionStyle = UITableViewCellSelectionStyleNone;
        ySingleCell.ySingleCollectModel = self.dataSource[indexPath.row];
        
        return ySingleCell;
    }
    
    
}


#pragma mark --------- 点击下载、收藏的view
- (void)chooseCount:(NSInteger)count WithTitle:(NSString *)title {
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        if (count == 0) {
            MusicYue_V_Model *musicModel = self.mvCollectArr[self.count];
            
            STLZhuangTai stl = [self.coreDataManager selectData:musicModel.hdUrl WithName:@"MvLoad"];
            if (stl == STLHave) {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"您已经下载过此MV" preferredStyle:  UIAlertControllerStyleAlert];
                
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    
                }]];
                //弹出提示框；
                [self presentViewController:alert animated:true completion:nil];
                
                
            }else {
                
                MvLoad *mvload = [NSEntityDescription insertNewObjectForEntityForName:@"MvLoad" inManagedObjectContext:self.coreDataManager.managedObjectContext];
                
                mvload.url = musicModel.hdUrl;
                mvload.title = musicModel.title;
                mvload.picture = musicModel.posterPic;
                
                [self.coreDataManager saveContext];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"已添加至下载队列" preferredStyle:  UIAlertControllerStyleAlert];
                
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    [self startload:musicModel.hdUrl];
                    
                    [self.coreDataManager saveContext];
                }]];
                //弹出提示框；
                [self presentViewController:alert animated:true completion:nil];
            }
        }

    }
}



#pragma mark -------------开始下载
- (void)startload:(NSString *)url{
    
    [[STLLoadMv sharedInstance]download:url progress:^(CGFloat progress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
        
    } state:^(DownloadState state) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
        });
        
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        
//        self.avPlayer.pageType = 2;
        ChannelPageMV_ViewController *channelPageMV_VC = [[ChannelPageMV_ViewController alloc] init];
        MusicYue_V_Model *model = self.dataSource[indexPath.row];
        channelPageMV_VC.idName = [NSString stringWithFormat:@"%@", model.idName];
        channelPageMV_VC.imageViewUrl = model.albumImg;
        [self.navigationController pushViewController:channelPageMV_VC animated:YES];
        
    } else {
        
//        self.avPlayer.pageType = 1;
        YMVViewController *yMVVC = [[YMVViewController alloc] init];
        
        YSingleCollectModel *model = self.dataSource[indexPath.row];
        
        HomePageBaseModel *homeModel = [[HomePageBaseModel alloc] init];
        homeModel._id = model.Id;
//        homeModel.title = model.title;
//        homeModel.totalViews = [NSString stringWithFormat:@"%@", model.totalViews];
//        homeModel.artistName = model.artistName;
//        homeModel.albumImg = model.listPic;
        
        yMVVC.homeModel = homeModel;
        [self.navigationController pushViewController:yMVVC animated:YES];

    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
